package org.gameis.furtal.server;

import org.gameis.furtal.FurtalConstants;
import org.gameis.furtal.server.network.ConnectionHandler;
import org.gameis.furtal.utils.FurtalUtils;

import javax.net.ServerSocketFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: zvoykish
 * Date: 27/1/12
 * Time: 12:12 PM
 */
public class Server {
    private List<ConnectionHandler> handlers;
    private List<Thread> threads;

    public Server() {
        handlers = new ArrayList<ConnectionHandler>();
        threads = new ArrayList<Thread>();
    }

    public void start() throws IOException {
        FurtalUtils.print("Server started");
        ServerSocket serverSocket = new ServerSocket(FurtalConstants.SERVER_PORT);
//        ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(FurtalConstants.SERVER_PORT);
        boolean running = true;
        while (running) {
            try {
                FurtalUtils.print("Listenning to clients");
                Socket socket = serverSocket.accept();
                FurtalUtils.print("Client connected from: " + socket.getInetAddress());
                ConnectionHandler connectionHandler = new ConnectionHandler(socket);
                Thread thread = new Thread(connectionHandler);
                handlers.add(connectionHandler);
                threads.add(thread);
                thread.start();
            } catch (IOException e) {
                running = false;
                e.printStackTrace();
            }
        }
        for (ConnectionHandler handler : handlers) {
            try {
                handler.getSocket().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FurtalUtils.print("Server closed");
    }

    public static void main(String[] args) {
        try {
            new Server().start();
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
